package org.springblade.modules.admin.utils.erp;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author Sharry
 */
public class Decrypt {

	private final byte[] keyBytes;

    public Decrypt(String key) {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            // exception
        }
		assert digest != null;
		keyBytes = digest.digest(key.getBytes(StandardCharsets.UTF_8));
    }

    public String decrypt(String base64) throws Exception {
        // base64 decode
        byte[] decode = Base64.getDecoder().decode(base64);
        Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
        // iv
        byte[] iv = new byte[16];
        System.arraycopy(decode, 0, iv, 0, 16);
        byte[] data = new byte[decode.length - 16];
        System.arraycopy(decode, 16, data, 0, data.length);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, "AES"), new IvParameterSpec(iv));
        byte[] result = cipher.doFinal(data);
        if (result.length > 0) {
            int len = result.length - 1;
			int decryptLength = 16;
			for (; len >= 0 && result[len] <= decryptLength; len--) {
            }
            if (len != result.length - 1) {
                byte[] tmp = new byte[len + 1];
                System.arraycopy(result, 0, tmp, 0, len + 1);
                result = tmp;
            }
        }
        return new String(result, StandardCharsets.UTF_8);
    }
}
